package com.z1.core.web.util.mybatis.shard.strategy;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.code.shardbatis.strategy.ShardStrategy;

public abstract class DateTimeStrategy extends ShardStrategy {

	//日期时间格式
	private String format = "yyyyMMdd";
	private DateFormat dateFormat = new SimpleDateFormat(format);

	public String getFormat() {
		return format;
	}
	public void setFormat(String format) {
		this.format = format;
		this.dateFormat = new SimpleDateFormat(format);
	}

	/**
	 * 得到实际表名
	 * @param baseTableName 基础表
	 * @param params mybatis执行某个statement时使用的参数
	 * @param mapperId mybatis配置的statement id
	 * @return
	 */
	@Override
	public String[] getTargetTableNames(String baseTableName, Object params, String mapperId) {
        Date[] dates = getDates(params, mapperId);
        if (null != dates) {
        	String[] tables = new String[dates.length];
        	for (int i = 0; i < tables.length; i++) {
        		if (null == dates[i]) { continue; }
        		String subfix = dateFormat.format(dates[i]);
        		tables[i] = baseTableName + "_" + subfix;
        	}
        	return tables;
        }
        return new String[] { baseTableName };
	}
	
	protected abstract Date[] getDates(Object params, String mapperId);

}
